import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	WeaSelect,
	WeaInputSearch,
	WeaLocaleProvider,
} from 'ecCom';
import {
	message,
	Button,
	Modal,
} from 'antd';
import trim from 'lodash/trim';
import cloneDeep from 'lodash/cloneDeep';
import * as api from '../apis/addressBook';
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
const {
	TableStore
} = WeaTableNew;

class AddressBook {
	@observable rConf = [];

	@action getRightMenu = (isEdit) => {
		api.getRightMenu().then(data => {
			const {
				rightMenus
			} = data;

			this.rConf = rightMenus;
		}, error => {})
	}

	@computed get dropMenuDatas() {
		const {
			comsWeaTableStore
		} = this.table;
		return this.rConf.map((item, index) => {
			const {
				menuFun,
				menuName,
				menuIcon
			} = item;

			return {
				key: menuFun,
				disabled: comsWeaTableStore.loading,
				icon: <i className={`${menuIcon}`} />,
				content: menuName,
				onClick: () => this[menuFun]()
			}
		});
	}

	doSearch = () => {
		this.onSearch();
	}

	reSearch = () => {
		this.setShowSearchAd(true);
	}

	definedColumn = () => {
		const {
			comsWeaTableStore
		} = this.table;
		comsWeaTableStore.setColSetVisible(true);
		comsWeaTableStore.tableColSet(true);
	}


	@observable radio = {
		currentIndex: 0,
		list: [],
	};

	@action getSubcompanyList = (callback) => {
		const getDefaultTypeAndId = (datas) => {
			const data = datas.filter(data => data.selected);

			let target;
			if (data) {
				target = data[0];
			} else {
				target = datas[0];
			}

			return target;
		}

		api.getSubcompanyList().then(datas => {
			const {
				subcompanyList
			} = datas;

			const target = getDefaultTypeAndId(subcompanyList);
			this.subCompanyId = target.id;
			const selectedSubcompanyIndex = subcompanyList.findIndex(item=>item.id===target.id);
			if(selectedSubcompanyIndex > 4){
				this.radio.currentIndex = selectedSubcompanyIndex - 4;
			}
			['id', 'type'].forEach(v => {
				this.orgTree[v] = target[v];
			});
			Object.assign(this.orgTree, {
				isLoadSubNode: '0'
			});
			this.radio.list = subcompanyList;
			this.trigger();
			callback && callback();
		}, error => {})
	}

	@action handleRadioGroupChange = (datas) => {
		const {
			target
		} = datas, {
			value
		} = target;
		this.subCompanyId = value;
		this.orgTree.id = value;
		this.orgTree.type = '1';
		Object.assign(this.orgTree, {
			isLoadSubNode: '0'
		});
		this.trigger();
		this.getSearchList();
	}

	@computed get radioConfigLength() {
		return this.radio.list.length;
	}

	@computed get hasArrow() {
		return this.radioConfigLength > 5;
	}

	@computed get radioConfigs() {
		const {
			list,
			currentIndex,
		} = this.radio;
		if (this.radioConfigLength > 5) {
			const startIndex = currentIndex;
			const endIndex = startIndex + 5;
			return list.slice(startIndex, endIndex);
		} else {
			return list;
		}
	}

	@computed get hasCheckedSubcompany() {
		return this.radioConfigs.find(config => config.id === this.subCompanyId);
	}

	showLeft = () => {
		const {
			currentIndex
		} = this.radio;
		if (currentIndex > 0) {
			this.radio.currentIndex = currentIndex - 1;
		}
		if (!this.hasCheckedSubcompany) {
			this.setDefaultSubcompany();
		}
	}

	showRight = () => {
		const {
			currentIndex
		} = this.radio;
		const rightIndex = currentIndex + 4;
		if (rightIndex + 1 < this.radioConfigLength) {
			this.radio.currentIndex = currentIndex + 1;
		}
		if (!this.hasCheckedSubcompany) {
			this.setDefaultSubcompany();
		}
	}

	setDefaultSubcompany = () => {
		const firstSubcompanyId = this.radioConfigs[0].id;
		this.handleRadioGroupChange({
			target: {
				value: firstSubcompanyId
			}
		});
	}

	buttonsAds = [getLabel(82529, '搜索'), getLabel(505324, '常用条件定制'), getLabel(27088, '重置'), getLabel(32694, '取消')];

	TAB = {
		advanceHeight: 310,
		hasMask: false,
		searchType: ['base', 'advanced'],
		setShowSearchAd: bool => this.setShowSearchAd(bool),
		onSearch: () => this.onSearch(),
		onSearchChange: val => this.onSearchChange(val),
		buttonsAd: this.buttonsAds.map((name, index) => {
			const type = [0, 1].includes(index) && "primary";
			let callback;
			if (index === 0) {
				callback = () => this.onSearch();
			} else if (index === 1) {
				callback = () => {
					const callback = () => {
						this.dialog.title = getLabel(505324, '常用条件定制');
						this.formatTransfer();
					}
					this.openDialog(callback);
				};
			} else if (index === 2) {
				callback = () => this.tab.form.resetConditionValue();
			} else {
				callback = this.setShowSearchAd
			}
			return <Button type={type} onClick={() => callback(index === 3 && false)}>{name}</Button>
		})
	}

	@observable tab = {
		showSearchAd: false,
		form: new WeaForm(),
		defaultcondition: [],
		condition: [],
		showAll: false,
	}

	@computed get searchsBaseValue() {
		const {
			form
		} = this.tab;
		return form.getFormParams().resourcename;
	}

	@observable setShowSearchAd = (bool) => {
		this.tab.showSearchAd = bool;
	}

	@action onSearch = () => {
		this.getSearchList('adSearch');
		this.setShowSearchAd(false);
	}

	@observable onSearchChange = (val) => {
		const {
			form
		} = this.tab;

		form.updateFields({
			resourcename: val
		});
	}

	@action getSearchCondition = (callback) => {
		api.getSearchCondition().then(datas => {
			const {
				defaultcondition,
				condition
			} = datas;

			this.tab.form = new WeaForm();
			this.tab.form.setCondition(defaultcondition);
			['defaultcondition', 'condition'].forEach(v => {
				this.tab[v] = datas[v];
			});
			callback && callback();
		}, error => {})
	}

	@computed get searchsAd() {
		const {
			form,
			showAll,
		} = this.tab;
		return (
			<div>
				{form.render()}
				<div className='allCondition'>
					<span onClick={this.renderCondition}>{`${showAll ?getLabel(505325,'常用条件'):getLabel(505326,'全部条件')} >>`}</span>
				</div>
			</div>
		);
	}

	renderCondition = () => {
		const {
			condition,
			defaultcondition,
			showAll,
		} = this.tab;
		this.tab.form = new WeaForm();
		let c;
		if (showAll) {
			c = defaultcondition;
		} else {
			c = condition;
		}
		this.tab.form.setCondition(c);
		this.tab.showAll = !showAll;
	}

	ORGTREE = {
		dataUrl: '/api/hrm/orgtree/getOrganizationTree',
		noCache: true,
		isLoadSubDepartment: true,
		treeNodeClick: (event, ids, nodeids, nodes) => this.handleOrgTreeNodeClick(event, ids, nodeids, nodes)
	}

	@observable subCompanyId = '';

	@observable orgTree = {
		id: '',
		type: '',
		isLoadSubNode: '0'
	}

	@observable triggerRefresh = false;

	@action trigger = (callback) => {
		this.triggerRefresh = !this.triggerRefresh;
		callback && callback();
	}

	handleOrgTreeNodeClick = (event, ids, nodeids, nodes) => {
		const id = ids[0];
		const type = nodes[0].type;

		if (type === '1') {
			this.subCompanyId = id;
		}
		this.orgTree.id = id;
		this.orgTree.type = type;

		this.setShowSearchAd(false);
		this.getSearchList();
	}

	@computed get orgTreeParams() {
		return this.orgTree;
	}

	@action resetOrgTreeParams = () => {
		Object.assign(this.orgTree, {
			isLoadSubNode: '1'
		});
	}

	DIALOG = {
		hasScroll: false,
		icon: 'icon-coms-hrm',
		iconBgcolor: '#217346',
		onCancel: () => this.closeDialog(),
		style: {
			width: 700,
			height: 450
		},
		moreBtn: {
			datas: []
		},
		buttons: [<Button type='primary' onClick={()=>this.saveHrmSearchUserDefine()}>{getLabel(505327,'保存')}</Button>],
	}

	@observable dialog = {
		visible: false,
		title: '',
	}

	@action openDialog = (callback) => {
		this.dialog.visible = true;
		callback && callback();
	}

	@action closeDialog = () => {
		this.dialog.visible = false;
	}

	TRANSFER = {
		height: 350,
		renderItem: (items) => this.renderItem(items),
		filterLeft: (items) => this.filterLeft(items),
		filterRight: (items) => this.filterRight(items),
		onChange: (v) => this.updateTransferKeys(v)
	}

	@observable transfer = {
		transferDatas: [],
		transferKeys: [],
		transferOptions: [],
		transferSelectedKey: '0',
		transferleftIptVal: '',
		transferRightIptVal: ''
	}

	@computed get leftHeader() {
		const {
			transferleftIptVal,
			transferOptions,
			transferSelectedKey
		} = this.transfer;
		return (
			<div className="trasfer-header">
	          <span>{getLabel(83302, '待选')}</span>
	          <WeaInputSearch
	            value={transferleftIptVal}
	            onSearchChange={this.updateTransferleftIptVal}
	          />
	          <WeaSelect
	            options={transferOptions}
	            value={transferSelectedKey}
	            onChange={this.updateTransferSelectedKey}
	          />
	        </div>
		)
	}

	@computed get rightHeader() {
		const {
			transferRightIptVal
		} = this.transfer;
		return (
			<div className="trasfer-header">
              <span>{ getLabel(83303, '已选')}</span>
              <WeaInputSearch
                value={transferRightIptVal}
                onSearchChange={ this.updateTransferRightptVal}
              />
            </div>
		)
	}
	renderItem = (item) => {
		const {
			label,
			title
		} = item;
		return (<div className="trasfer-list-item">
		      <div className="top text-overflow" title={label}>{label}</div>
		      <div className="bottom text-overflow" title={title}>{title}</div>
		    </div>)
	};

	filterLeft = (items) => {
		let leftItems = cloneDeep(items);
		const {
			transferleftIptVal,
			transferSelectedKey
		} = this.transfer;
		if (transferSelectedKey) {
			leftItems = leftItems.filter((item) => item.idx == transferSelectedKey)
		}
		if (trim(transferleftIptVal)) {
			leftItems = leftItems.filter((item) => item.label.indexOf(trim(transferleftIptVal)) > -1)
		}
		return leftItems
	}

	filterRight = (items) => {
		let rightItems = cloneDeep(items);
		const {
			transferRightIptVal
		} = this.transfer;
		if (trim(transferRightIptVal)) {
			rightItems = rightItems.filter((item) => item.label.indexOf(trim(transferRightIptVal)) > -1)
		}
		return rightItems
	}

	@action formatTransfer = () => {
		const transferDatas = []
		const transferKeys = []
		const transferOptions = [{
			key: "",
			showname: ""
		}]
		this.transfer.transferSelectedKey = '0';
		this.transfer.transferleftIptVal = '';
		this.transfer.transferRightIptVal = '';
		this.tab.condition.forEach((c, idx) => {
			transferOptions.push({
				key: `${idx}`,
				showname: c.title,
			})
			c.items.forEach((i) => {
				transferDatas.push({
					id: i.domkey[0],
					label: i.label,
					title: c.title,
					idx: `${idx}`
				})
			})
		})
		this.tab.defaultcondition.forEach((c, idx) => {
			c.items.forEach((i) => {
				transferKeys.push(i.domkey[0]);
			})
		})
		this.transfer.transferDatas = transferDatas;
		this.transfer.transferKeys = transferKeys;
		this.transfer.transferOptions = transferOptions;
	}

	@action updateTransferKeys = (v) => {
		this.transfer.transferKeys = v;
	}

	@action updateTransferleftIptVal = (v) => {
		this.transfer.transferleftIptVal = v;
	}

	@action updateTransferSelectedKey = (v) => {
		this.transfer.transferSelectedKey = v;
	}

	@action updateTransferRightptVal = (v) => {
		this.transfer.transferRightIptVal = v;
	}

	saveHrmSearchUserDefine = () => {
		const params = {};
		const {
			transferKeys
		} = this.transfer;
		transferKeys.forEach(c => {
			if (c.endsWith("select")) {
				c = c.replace("select", "");
			}
			const paramName = "has" + c;
			Object.assign(params, {
				[paramName]: '1'
			});
		});
		api.saveHrmSearchUserDefine(params).then(data => {
			if (data.status == '1') {
				this.closeDialog();
				this.setShowSearchAd(false);
				this.getSearchCondition();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	TABLE = {
		hasOrder: true,
		needScroll: true,
	}

	@observable table = {
		comsWeaTableStore: new TableStore(),
	}

	@action getSearchList = (source) => {
		const {
			form
		} = this.tab, {
			id,
			type
		} = this.orgTree;
		const params = {
			...form.getFormParams()
		}
		if (source !== 'adSearch') {
			if (type === '1') {
				Object.assign(params, {
					subcompanyid1: id,
				});
			}
			if (type === '2') {
				Object.assign(params, {
					departmentid: id,
				});
			}
		}
		api.getSearchResult(params).then((data) => {
			const {
				sessionkey
			} = data;
			this.table.comsWeaTableStore = new TableStore();
			this.table.comsWeaTableStore.getDatas(sessionkey, 1);
		});
	}

}

export const addressBook = new AddressBook();